
var cache = {};

function edit(tdId) {
    if (cache[tdId]) {
        cancel(tdId);
        return;
    }

    cache[tdId] = $('#n_' + tdId).html();

    var input = '<input type="text" />';
    var btnOk = '<a href="#" onclick="save(\'' + tdId + '\');return false;"><img class="action" title="Запис" src="' + staticUrl + '/img/ok.gif" /></a>';
    var btnCancel = '<a href="#" onclick="cancel(\'' + tdId + '\');return false;"><img class="action" title="Отказ" src="' + staticUrl + '/img/cancel.gif" /></a>';

    $('#n_' + tdId).html(input + btnOk + btnCancel);
    $('#n_' + tdId + ' input')
        .val(cache[tdId])
        .focus()
        .bind('keypress', function(e) {
            switch (e.keyCode) {
                case 13: save(tdId); break;
                case 27: cancel(tdId); break;
            }
        });
}

function save(tdId) {
    var value = $('#n_' + tdId + ' input').val();
    $.post(
        '/' + page + '/edit',
        {id: tdId, name: value},
        function(data) {
            if (data) { // error
                $('#n_' + tdId).html(cache[tdId]);
                cache[tdId] = null;
                alert('Невалидно име');
            } else {
                $('#n_' + tdId).html(value);
                cache[tdId] = null;
            }
        }
    );
}

function cancel(tdId) {
    $('#n_' + tdId).html(cache[tdId]);
    cache[tdId] = null;
}

function trim (str) {
    str = str.replace(/^\s+/, '');

    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }

    return str;
}


function add() {
    var value = trim($('#name').val());

    if (!value) {
        alert('Невалидно име');
        return false;
    }

    return true;
}

$(document).ready(function() {
    var i = 0;
    $('table.simple tbody tr').each(function() {
        $(this).addClass(i++ % 2 ? 'even' : 'odd');
    });
});
